﻿using Common.Logging;
using Microsoft.Practices.Unity.InterceptionExtension;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web.Script.Serialization;

namespace Common.Object
{

    public static class ObjectHelper
    {
        public static string ToString(this ParameterInfo[] parameters, IMethodInvocation method)
        {
            string str = string.Empty;
            for (int i = 0; i < parameters.Length; i++)
            {
                string val = string.Empty;
                object data = method.Arguments[i] ?? null;
                IgnoreLoggerAttribute attr = parameters[i].GetCustomAttribute<IgnoreLoggerAttribute>();
                if (attr != null) val = "***";
                else
                {
                    if (data != null && (parameters[i].ParameterType.IsArray || typeof(IEnumerable<object>).IsAssignableFrom(parameters[i].ParameterType)))
                        val = string.Format("{{{0}}}", string.Join(",", ((IEnumerable<object>)data).Select(v => (v == null) ? "null" : v.ToString())));
                    else val = (data == null) ? "null" : data.ToString();
                }
                str += string.Format(",{0}:{1}", parameters[i].Name, val);
            }
            return str.Equals(string.Empty) ? string.Empty : str.Substring(1);
        }

        public static string ToJson(this object obj)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            if (obj == null) return "null";
            return jss.Serialize(obj);
        }

        public static T JsonToObject<T>(this string jsonString) where T : class
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            return jss.Deserialize<T>(jsonString);
        }

        public static string ToJsonString(this IDictionary dict)
        {
            string st = string.Empty;
            foreach(string key in dict.Keys)
            {
                st+=string.Format(",\"{0}\":{1}",key,(dict[key]==null)?"null":("\""+dict[key].ToString()+"\""));
            }
            if (!st.Equals(string.Empty)) st = st.Substring(1);
            return "{" + st + "}";
        }

    }
}
